package com.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dto.CartSaveDto;
import com.po.Cart;
import com.result.Result;
import com.service.CartService;
import com.vo.CartVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/cart/")
public class CartController {

    private final CartService cartService;

    /**
     * 加入购物车
     * @param cartSaveDto
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody CartSaveDto cartSaveDto){
        log.info("加入购物车：{}",cartSaveDto);
        Cart cart = new Cart();
        BeanUtil.copyProperties(cartSaveDto,cart);
        cart.setUserId(StpUtil.getLoginIdAsLong());
        cart.setCreateTime(LocalDateTime.now());
        cartService.save(cart);
        return Result.success();
    }

    /**
     * 商品购物车加一
     * @param id
     * @return
     */
    @PutMapping("add")
    public Result add(@RequestParam Long id){
        log.info("购物车加一：{}",id);
        UpdateWrapper<Cart> wrapper = new UpdateWrapper<Cart>()
                .setSql("num = num + 1")
                .in("id", id);
        cartService.update(null,wrapper);
        return Result.success();
    }

    /**
     * 商品购物车减一
     * @param id
     * @return
     */
    @PutMapping("less")
    public Result less(@RequestParam Long id){
        log.info("购物车减一：{}",id);
        UpdateWrapper<Cart> wrapper = new UpdateWrapper<Cart>()
                .setSql("num = num - 1")
                .in("id", id);
        cartService.update(null,wrapper);
        return Result.success();
    }

    /**
     * 一键清空购物车
     * @return
     */
    @DeleteMapping("delete")
    public Result delete(){
        log.info("一键清空购物车：");
        QueryWrapper<Cart> wrapper = new QueryWrapper<Cart>()
                .in("user_id", StpUtil.getLoginIdAsLong());
        cartService.remove(wrapper);
        return Result.success();
    }

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("get")
    public Result<List<CartVo>> get(){
        log.info("查询购物车：{}",StpUtil.getLoginIdAsLong());
        QueryWrapper<Cart> wrapper = new QueryWrapper<Cart>()
                .in("user_id", StpUtil.getLoginIdAsLong());
        List<Cart> cartList = cartService.list(wrapper);
        List<CartVo> cartVoList = new ArrayList<>();
        cartList.forEach(cart -> {
            CartVo cartVo = new CartVo();
            BeanUtil.copyProperties(cart,cartVo);
            cartVoList.add(cartVo);
        });
        return Result.success(cartVoList);
    }
}
